package com.mediastory.spsserver.users.web;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mediastory.spsserver.customer.service.CustomerSvc;
import com.mediastory.spsserver.users.domain.Users;
import com.mediastory.spsserver.users.service.UsersSvc;

/**
 * @author Jaewon Choi
 */

@Controller
@RequestMapping("/users")
public class UsersCtrl {
	
	private final Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private MessageSourceAccessor messages;
	
	@Autowired
	private UsersSvc usersSvc;
	
	@Autowired
	private CustomerSvc customerSvc;
	
	/**
	 * 목록 보기
	 * */
	@RequestMapping(value={"/list.do"})
	public Map<String, Object> list(HttpServletRequest request) throws Exception {
		Map<String, Object> condition = new HashMap<String, Object>();
		//검색 parameter
		String name = ServletRequestUtils.getStringParameter(request, "name");
		String id = ServletRequestUtils.getStringParameter(request, "id");
		condition.put("name", name);
		condition.put("id", id);

		//페이징 처리 parameter
		int maxnum = ServletRequestUtils.getIntParameter(request, "maxnum", 10);
		int page = ServletRequestUtils.getIntParameter(request, "page", 1);
		condition.put("maxnum", maxnum);
		condition.put("page", (page-1)*maxnum);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.putAll(usersSvc.findbyListPaging(condition));
		resultMap.put("maxnum", maxnum);
		resultMap.put("page", page);
		
		return resultMap;
	}

	/**
	 * 등록 폼, 이용자 상세 보기
	 * */
	@RequestMapping(value={"/form.do"})
	public Map<String, Object> form(HttpServletRequest request) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		int idx = ServletRequestUtils.getIntParameter(request, "idx", 0);
		if(idx != 0){
			resultMap.put("users", usersSvc.findby(idx));
		}
		
		Map<String, Object> condition = new HashMap<String, Object>();
		resultMap.put("customerList", customerSvc.findbyList(condition));
		
		return resultMap;
	}
	
	/**
	 * 이용자 등록/수정
	 * */
	@RequestMapping(value={"/submit.do"}, method=RequestMethod.POST)
	public String submit(Users users, HttpSession session, HttpServletRequest request) throws Exception {
		String userId = (String)session.getAttribute("userId");
		String ip = request.getRemoteAddr();
		String userPw = users.getPassword();
		
		if(users.getId() == null || ! (users.getId()!=null && users.getId().length() >= 4 && users.getId().length() <= 15)){
			throw new Exception("[ERROR] 아이디는 4자리 이상 15자리 입력하셔야 합니다.");
		}
		
		if(userPw == null || ! (userPw!=null && userPw.length() >= 8 && userPw.length() <= 15)){
			throw new Exception("[ERROR] 비밀번호는 8자리 이상이어야 합니다.");
		}
		
		MessageDigest messageDigest = MessageDigest.getInstance("MD5");
		messageDigest.update(userPw.getBytes(),0, userPw.length());  
		String hashedPass = new BigInteger(1,messageDigest.digest()).toString(16);  
		if (hashedPass.length() < 32) {
		   hashedPass = "0" + hashedPass; 
		}
		users.setPassword(hashedPass);
		
		if(users.getIdx() != null){
			users.setModifiedId(userId);
			users.setModifiedIp(ip);
			usersSvc.modify(users);
		}else{
			users.setCreatedId(userId);
			users.setCreatedIp(ip);
			usersSvc.add(users);
		}

		return "users/result";
	}
	
	/**
	 * 이용자 삭제
	 * */
	@RequestMapping(value={"/remove.do"}, method=RequestMethod.POST)
	public String remove(HttpServletRequest request) throws Exception {
		
		int[] idx = ServletRequestUtils.getIntParameters(request, "idx");
		
		if(idx.length == 0){
			throw new Exception("[ERROR] 삭제할 이용자를 하나 이상 선택하셔야 합니다.");
		}
		
		Map<String, Object> condition = new HashMap<String, Object>();
		
		condition.put("modifiedId", request.getUserPrincipal().getName());
		condition.put("idx", idx);
		
		usersSvc.remove(condition);
		return "users/result";
	}

	//@RequestMapping("/chkDupl.do")
	@RequestMapping(method=RequestMethod.POST, value="/chkDupl")
	//@RequestMapping(value={"/chkDupl"}, method=RequestMethod.POST)
	public @ResponseBody String chkDuplication(HttpSession session, @RequestParam(required=true, value="idx")  String idx, @RequestParam(required=true, value="chkId")  String id) throws Exception {
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("chkDupl", true);
		condition.put("idx", idx);
		condition.put("id", id);
		return usersSvc.findbyChkDupl(condition);
	}

}